var path = require('path')
var fs = require('fs')
var Router = require('koa-router')
var jwt = require('koa-jwt')
var mongoose = require('mongoose')
var tools = require('./lib/tools')
var config = require('./config')
var logger = require('./lib/logger')('app')

logger.debug('config: %j', config)
var app = require('koa')()

mongoose.connect(tools.createConnStr(config.mongodb))
mongoose.connection.on('error', (err) => {
  logger.error(err)
  process.exit(1)
})

app.use(require('koa-cors')())
app.use(require('koa-body')())
require('koa-validate')(app)

app.context.config = config
app.context.apiError = tools.apiError
app.context.apiSuccess = tools.apiSuccess

app.use(function * (next) {
  logger.info('%s', this.method, this.path)
  yield next
})

app.use(jwt({secret: config.app.jwt_secret}).unless({path: /^\/jwt/}))

var router = new Router()
fs.readdirSync(path.join(__dirname, 'apis'))
  .forEach((filename) => {
    require(path.join(__dirname, 'apis', filename))(router)
  })

app.listen(config.app.port, () => {
  logger.info('Server is listening on %s', config.app.port)
})
